package com.example.takeaway.filter;

import com.alibaba.fastjson.JSON;
import com.example.takeaway.common.R;
import com.example.takeaway.constant.CacheNames;
import com.example.takeaway.context.UserInfoContext;
import com.example.takeaway.model.bo.UserAccount;
import com.example.takeaway.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 邢晨旭
 * {@code @date} 2023/10/16
 */
@Component
@Slf4j
public class AuthFilter extends HttpFilter {


    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            response.setCharacterEncoding("UTF-8");
            boolean isLogin = false;
            String token = request.getHeader("Authorization");
            if (token != null) {
                String userJson = RedisUtil.get(CacheNames.LOGIN_USER_INFO + token);
                if (userJson != null) {
                    isLogin = true;
                    UserInfoContext.set(JSON.parseObject(userJson, UserAccount.class));
                }
            }
            String uri = request.getRequestURI();
            log.info("uri:{}", uri);
            if (uri.startsWith("/public") || uri.contains("login") || uri.startsWith("/ws")) {
                chain.doFilter(request, response);
                return;
            }
            if (!isLogin) {
                response.getWriter().write(JSON.toJSONString(R.err().message("请先登录")));
                return;
            }
            chain.doFilter(request, response);
        } finally {
            UserInfoContext.remove();
        }

    }
}
